package com.csproj.basic;

import com.csproj.basic.domain.ElectronicLock;
import com.csproj.basic.domain.Site;
import com.csproj.basic.domain.Warehouse;
import com.csproj.basic.repository.SiteRepository;
import com.csproj.basic.repository.WarehouseRepository;
import com.csproj.siiat.base.common.util.ReflectFactory;
import com.csproj.siiat.security.SecurityUtils;
import com.csproj.system.domain.Dictionary;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.repository.DictionaryRepository;
import com.csproj.system.repository.UserInfoRepository;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.dto.SysLogsDTO;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ==================================================
 * 创建人：LM
 * 创建时间：2017/12/6
 * ==================================================
 * 类说明：
 * <p>
 * ==================================================
 *
 * @version 1.0 2017/12/6
 */
public class BasicService<T> {

    @Resource(name = "siteRepository")
    private SiteRepository siteRepository;

    @Resource(name = "dictionaryRepository")
    private DictionaryRepository dictionaryRepository;

    @Resource(name="userInfoRepository")
    private UserInfoRepository userInfoRepository;

    @Resource(name="warehouseRepository")
    private WarehouseRepository warehouseRepository;

    /**
     * 扩展siteName
     * @return
     */
    public BasicService<T> extendSiteName(T dtoObject){
        String dtoObjectResourceParam = "siteId";//dto对象的原本属性
        String dtoObjectResultParam = "siteName";//dto对象的转换属性

        String siteId = String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam));
        Site site = siteRepository.findOne(siteId);
        if(site != null){
            setAttribute(dtoObject, dtoObjectResultParam,site.getSiteName());
        }
        return this;
    }

    /**
     * 扩展siteName
     * @return
     */
    public BasicService<T> extendSiteName(List<T> dtoObjects,String dtoObjectResourceParam,String dtoObjectResultParam){
        if(dtoObjects.size()==0){
            return this;
        }

        //获取用户的集合
        List<String> siteIdList = dtoObjects.stream().map(dtoObject -> String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))
                .collect(Collectors.toList());
        String[] siteIds = siteIdList.toArray(new String[siteIdList.size()]);
        List<Site> siteList = siteRepository.findByIds(siteIds);

        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            siteList.stream().forEach(site -> {
                if(String.valueOf(site.getId()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, site.getSiteName());
                }
            });
        });
        return this;
    }

    /**
     * 扩展siteTypeName
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendDictionaryTypeName(List<T> dtoObjects,String dtoObjectResourceParam,String dtoObjectResultParam,String key){
        if(dtoObjects.size()==0){
            return this;
        }
        List<Dictionary> electronicLockList = dictionaryRepository.getDictListByType(key);
        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            electronicLockList.stream().forEach(dictionary -> {
                if(String.valueOf(dictionary.getItemKey()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, dictionary.getItemValue());
                }
            });
        });
        return this;
    }

    /**
     * 扩展siteName
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendSiteName(List<T> dtoObjects){
        if(dtoObjects.size()==0){
            return this;
        }
        String dtoObjectResourceParam = "siteId";//dto对象的原本属性
        String dtoObjectResultParam = "siteName";//dto对象的转换属性

        //获取用户的集合
        List<String> siteIdList = dtoObjects.stream().map(dtoObject -> String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))
            .collect(Collectors.toList());
        String[] siteIds = siteIdList.toArray(new String[siteIdList.size()]);
        List<Site> siteList = siteRepository.findByIds(siteIds);

        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            siteList.stream().forEach(site -> {
                if(String.valueOf(site.getId()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, site.getSiteName());
                }
            });
        });
        return this;
    }

    /**
     * 扩展companyName
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendCompanyName(List<T> dtoObjects){
        if(dtoObjects.size()==0){
            return this;
        }
        String dtoObjectResourceParam = "containerCompanyId";//dto对象的原本属性
        String dtoObjectResultParam = "containerCompanyName";//dto对象的转换属性

        //获取用户的集合
        List<String> companyIdList = dtoObjects.stream().map(dtoObject -> String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))
                .collect(Collectors.toList());
        String[] companyIds = companyIdList.toArray(new String[companyIdList.size()]);
        List<Warehouse> companyList = warehouseRepository.findByIds(companyIds);

        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            companyList.stream().forEach(company -> {
                if(String.valueOf(company.getId()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, company.getHouseName());
                }
            });
        });
        return this;
    }

    /**
     * 扩展companyName
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendCompanyName(List<T> dtoObjects, String dtoObjectResourceParam ,String dtoObjectResultParam ){
        if(dtoObjects.size()==0){
            return this;
        }
        //获取用户的集合
        List<String> companyIdList = dtoObjects.stream().map(dtoObject -> String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))
                .collect(Collectors.toList());
        if(companyIdList.size()==0){
            return this;
        }
        String[] companyIds = companyIdList.toArray(new String[companyIdList.size()]);
        List<Warehouse> companyList = warehouseRepository.findByIds(companyIds);

        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            companyList.stream().forEach(company -> {
                if(String.valueOf(company.getId()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, company.getHouseName());
                }
            });
        });
        return this;
    }

    /**
     * 扩展StateNameOfElectronicLock
     * @return
     */
    public BasicService<T> extendStateNameOfElectronicLock(T dtoObject){
        String dtoObjectResourceParam = "state";//dto对象的原本属性
        String dtoObjectResultParam = "stateName";//dto对象的转换属性

        String state = getAttribute(dtoObject, dtoObjectResourceParam);
        Dictionary dictionary = dictionaryRepository.getDictListByTypeAndItemKey("electronicLock_state", state);
        if(dictionary != null){
            setAttribute(dtoObject, dtoObjectResultParam,dictionary.getItemValue());
        }
        return this;
    }


    /**
     * 扩展StateNameOfElectronicLock
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendStateNameOfElectronicLock(List<T> dtoObjects){
        if(dtoObjects.size()==0){
            return this;
        }
        String dtoObjectResourceParam = "state";//dto对象的原本属性
        String dtoObjectResultParam = "stateName";//dto对象的转换属性

        List<Dictionary> electronicLockList = dictionaryRepository.getDictListByType("electronicLock_state");
        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            electronicLockList.stream().forEach(dictionary -> {
                if(String.valueOf(dictionary.getItemKey()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, dictionary.getItemValue());
                }
            });
        });
        return this;
    }

    /**
     * 扩展siteTypeName
     * @return
     */
    public BasicService<T> extendSiteTypeName(T dtoObject){
        String dtoObjectResourceParam = "siteType";//dto对象的原本属性
        String dtoObjectResultParam = "siteTypeName";//dto对象的转换属性

        String state = getAttribute(dtoObject, dtoObjectResourceParam);
        Dictionary dictionary = dictionaryRepository.getDictListByTypeAndItemKey("site_type", state);
        if(dictionary != null){
            setAttribute(dtoObject, dtoObjectResultParam,dictionary.getItemValue());
        }
        return this;
    }


    /**
     * 扩展siteTypeName
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendSiteTypeName(List<T> dtoObjects){
        if(dtoObjects.size()==0){
            return this;
        }
        String dtoObjectResourceParam = "siteType";//dto对象的原本属性
        String dtoObjectResultParam = "siteTypeName";//dto对象的转换属性

        List<Dictionary> electronicLockList = dictionaryRepository.getDictListByType("site_type");
        //循环匹配用户的id并设置名称
        dtoObjects.stream().forEach(dtoObject -> {
            electronicLockList.stream().forEach(dictionary -> {
                if(String.valueOf(dictionary.getItemKey()).equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))){
                    setAttribute(dtoObject, dtoObjectResultParam, dictionary.getItemValue());
                }
            });
        });
        return this;
    }

    public BasicService<T> extendManagerName(T  dtoObject){
        String dtoObjectResourceParam = "managerId";//dto对象的原本属性
        String dtoObjectResultParam = "manager";//dto对象的转换属性

        String userId = String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam));
        UserInfo user = userInfoRepository.findOne(userId);
        if(user != null){
            setAttribute(dtoObject, dtoObjectResultParam,user.getAccount());
        }
        return this;
    }

    /**
     * 扩展manager
     * @return
     * @param dtoObjects
     */
    public BasicService<T> extendManagerName(List<T> dtoObjects){
        if(dtoObjects.size()==0){
            return this;
        }
        String dtoObjectResourceParam = "managerId";//dto对象的原本属性
        String dtoObjectResultParam = "manager";//dto对象的转换属性

        //获取用户的集合
        List<String> userIdList = dtoObjects.stream().map(dtoObject -> String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam)))
                .collect(Collectors.toList());
        String[] userIds = userIdList.toArray(new String[userIdList.size()]);
        List<UserInfo> userInfoList = userInfoRepository.findByIds(userIds);

        //循环匹配用户的id并设置名称

        dtoObjects.stream().forEach(dtoObject -> {
                    if(StringUtils.isNotBlank(getAttribute(dtoObject, dtoObjectResourceParam))) {
                        UserInfo user = userInfoList.stream()
                                .filter(userInfo -> userInfo.getId().equals(String.valueOf(getAttribute(dtoObject, dtoObjectResourceParam))))
                                .findFirst().orElse(new UserInfo());
                        if(StringUtils.isNotBlank(user.getId()))
                        {
                            setAttribute(dtoObject, dtoObjectResultParam, user.getAccount());
                        }

                    }
        });
        return this;
    }


    /**
     * 获取方法属性
     * @param dtoObject
     * @param attribute
     * @return
     */
    private String getAttribute(T dtoObject, String attribute) {
        String getMethodName = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1); // 将属性的首字符大写，方便构造get，set方法
        Object value = new ReflectFactory<T>()
            .setObject(dtoObject)
            .setMethodName(getMethodName)
            .invoke();
        if(value != null){
            return value.toString();
        }
        return null;
    }


    /**
     * 设置方法属性
     * @param object
     * @param attribute
     * @param value
     */
    private void setAttribute(T object, String attribute, Object value) {
        String getMethodName = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1); // 将属性的首字符大写，方便构造get，set方法
        Object attributeValue = new ReflectFactory<T>()
            .setObject(object)
            .setMethodName(getMethodName)
            .invoke();
        if(attributeValue == null){
            String setMethodName = "set" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1); // 将属性的首字符大写，方便构造get，set方法
            new ReflectFactory<T>()
                .setObject(object)
                .setMethodName(setMethodName)
                .setParameterTypes(value.getClass())
                .setParameter(value)
                .invoke();
        }
    }

    public UserInfo getCurrentUser(){
        String userInfoId = SecurityUtils.getCurrentUserId();
        UserInfo userInfo = userInfoRepository.findOne(userInfoId);
        userInfo.setName(userInfo.getAccount());
        return  userInfo;
    }

//    public SysLogsDTO saveForGet(String rentId, String description, String moduleType ) {
//        return saveForGet(rentId,description,moduleType);
//    }
//
//    public SysLogsDTO saveForDelete(String rentId,String description,String moduleType ){
//        return saveForDelete(rentId,description,moduleType);
//    }
//    public SysLogsDTO saveForPut(String rentId,String description,String moduleType ){
//        return saveForPut(rentId,description,moduleType);
//    }
//    public SysLogsDTO saveForPost(String rentId,String description,String moduleType ){
//        return saveForPost(rentId,description,moduleType);
//    }
}
